<?php

namespace App\Service\product;

use App\Events\OrderEvent;
use App\Models\order\OrderModel;
use App\Models\product\ProductSonModel;
use App\Service\users\AccountRecordService;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use lxs\config\BaseStatic;

class OrderService extends BaseStatic
{

    /**
     * 创建订单
     * @param $data array 订单数据
     */
    public function updateOrderStatus(array $data): array
    {
        try {
            DB::beginTransaction();

            $orderInfo = OrderModel::where('order_sn', $data['order_sn'])->first();
            if (!$orderInfo) {
                $orderInfo = new OrderModel();
            }
            if ($orderInfo->order_status == 4) {
                return self::serviceReturn(400, '订单已退款, 不能更新订单状态!');
            }
            if ($orderInfo->order_status == 2) {
                return self::serviceReturn(400, '订单已完成, 不能更新订单状态!');
            }
            $orderInfo->order_sn = $data['order_sn'];
            $orderInfo->new_id = $data['new_id'];
            $orderInfo->uid = $data['uid'];
            $orderInfo->product_id = $data['product_id'];
            $orderInfo->order_commission_ratio = $data['order_commission_ratio'];
            $orderInfo->commission = $data['commission'];
            $orderInfo->order_status = $data['order_status'];
            $orderInfo->pay_price = $data['pay_price'];
            $orderInfo->pay_time = $data['pay_time'];
            $orderInfo->create_time = $data['create_time'];
            $orderInfo->update_time = $data['update_time'];
            $orderInfo->save();

            if (isset($orderInfo->id)) {
                $data['id'] = $orderInfo->id;
                event(new OrderEvent($data));
            }

            DB::commit();
            $message = match ($orderInfo->order_status) {
                0 => '订单(' . $orderInfo->order_sn . ')' . '订单创建成功',
                1 => '订单(' . $orderInfo->order_sn . ')' . '支付成功',
                2 => '订单(' . $orderInfo->order_sn . ')' . '已完成',
                3 => '订单(' . $orderInfo->order_sn . ')' . '订单已失效',
                4 => '订单(' . $orderInfo->order_sn . ')' . '已退款',
                default => '订单(' . $orderInfo->order_sn . ')' . '订单状态异常'
            };
            return self::serviceReturn(200, $message);
        } catch (\Throwable $e) {
            DB::rollBack();
            Log::error('订单生成失败：' . $e->getMessage() . $e->getLine() . $e->getFile());
            return self::serviceReturn(400, '更新订单失败');
        }

    }


}
